<template>
  <div
    class="chart-box"
    style="width: 100%; height: 100%"
    :style="{ backgroundColor: widgetOptions.setup.backgroundColor }"
  >
    <div v-if="!chartStatus" ref="chartRef" style="width: 100%; height: 100%"></div>
    <ChartEmpty v-if="chartStatus" :chartStatus="chartStatus" />
  </div>
</template>

<script lang="ts" setup>
import { useTools } from '../../../hooks/useTools'
import * as echarts from 'echarts'
import ChartEmpty from '../../../components/chartEmpty.vue'
import { TerminalDeviceApi } from '@/api/vmiot/terminaldevice'

// 接收父组件传入的值
const props = defineProps({
  widgetOptions: {
    type: Object as PropType<Record<string, any>>, // 或更具体的类型
    required: true
  },
  isPreview: {
    type: Boolean,
    default: false
  },
  tenantId: {
    type: Number,
    default: null
  }
})

const chartRef = ref<HTMLDivElement | null>(null)
let myChart: echarts.ECharts | null = null
const chartData = ref<any>(null)
const chartStatus = ref('')
const refreshInterval = ref<any>()
const { toRgba } = useTools()

const initChart = () => {
  if (chartRef.value) {
    // 初始化实例
    myChart = echarts.init(chartRef.value)
  }
}

// 更新配置
const updateOptions = () => {
  if (!chartData.value) return

  const onlineNum = chartData.value.find((item) => item.deviceState === 1)?.totalCount || 0
  const offlineNum = chartData.value.find((item) => item.deviceState === 2)?.totalCount || 0

  const option = {
    title: {
      text: '终端设备统计',
      left: 'center',
      textStyle: {
        color: props.widgetOptions.setup.titleColor,
        fontSize: props.widgetOptions.setup.titleFontSize
      }
    },
    tooltip: {
      trigger: 'item'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        color: props.widgetOptions.setup.legendFontColor,
        fontSize: props.widgetOptions.setup.legendFontSize
      }
    },
    series: [
      {
        name: '终端设备统计',
        type: 'pie',
        radius: '50%',
        label: {
          color: props.widgetOptions.setup.labelFontColor,
          fontSize: props.widgetOptions.setup.labelFontSize
        },
        data: [
          {
            value: onlineNum,
            name: '在线设备',
            itemStyle: {
              color: props.widgetOptions.setup.onlineColor
            }
          },
          {
            value: offlineNum,
            name: '离线设备',
            itemStyle: {
              color: props.widgetOptions.setup.offlineColor
            }
          }
        ]
      }
    ]
  }

  myChart?.setOption(option)
  myChart?.resize()
}

// 启动定时器
const startInterval = () => {
  if (props.widgetOptions.data.refreshTime > 0) {
    refreshInterval.value = setInterval(() => {
      getRealData()
    }, props.widgetOptions.data.refreshTime)
  }
}

const getRealData = async () => {
  try {
    const res = await TerminalDeviceApi.getCountGroupByDeviceState(props.tenantId)
    chartData.value = res
    updateOptions()
  } catch (e) {
    chartStatus.value = 'error'
  }
}

// 刷新数据
const refreshData = () => {
  if (props.isPreview) {
    getRealData()
    startInterval()
  } else {
    chartData.value = props.widgetOptions.data.statisticData
    updateOptions()
  }
}

onMounted(() => {
  initChart()
  refreshData()
})

// 如果父组件传入的 props.value 改变，需要更新折线图颜色等
watch(
  () => props.widgetOptions,
  () => {
    if (myChart) {
      updateOptions()
    }
  },
  { immediate: true, deep: true }
)

onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose()
  }
  clearInterval(refreshInterval.value)
})
</script>

<style scoped></style>
